package com.wyy.mall.tiny.controller;

import com.wyy.mall.tiny.common.api.CommonResult;
import com.wyy.mall.tiny.dto.UmsAdminLoginParam;
import com.wyy.mall.tiny.mbg.model.UmsAdmin;
import com.wyy.mall.tiny.mbg.model.UmsPermission;
import com.wyy.mall.tiny.service.UmsAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台用户管理
 * created by 伍猷煜 on 2021/5/14 17:48 星期五
 */
@Api(tags = "UmsAdminController", description = "后台用户管理")
@Controller
@RequestMapping("/admin")
public class UmsAdminController {

    @Autowired
    private UmsAdminService mUmsAdminService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    @ResponseBody
    // TODO 假设注册时，已经存在相同用户名，这时，仍然返回成功消息？只是值为null，
    //  如果注册成功，返回的是完整的UmsAdmin，且密码是加密后的，这合适？好像合适
    public CommonResult register(@RequestBody UmsAdmin umsAdmin, BindingResult result) {
        UmsAdmin ua = mUmsAdminService.register(umsAdmin);
        if (ua == null) return CommonResult.failed("注册失败");
        return CommonResult.success(ua, "注册成功");
    }

    @ApiOperation(value = "登录以后返回token")
    @PostMapping("/login")
    @ResponseBody
    public CommonResult login(@RequestBody UmsAdminLoginParam umsAdminLoginParam, BindingResult result) {
        String token = mUmsAdminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        if (token == null) return CommonResult.validateFailed("用户名或密码错误");
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "获取用户所有权限（包括+-权限）")
    @GetMapping("/permission/{adminId}")
    @ResponseBody
    public CommonResult<List<UmsPermission>> getPermissionList(@PathVariable Long adminId) {
        List<UmsPermission> permissions = mUmsAdminService.getPermissionList(adminId);
        return CommonResult.success(permissions);
    }
}
